/*
 * @description 全部节点
 * @fileName orderdetail.js
 * @date 2025/08/13 21:19:51
 */

const toggleAccount = () => {
  layui
    .$('form[lay-filter="change-same-area-form"] > div.layui-form-item:eq(1)')
    .toggle()
}

/**
 * 同地区调换
 * @isRandom 是否随机地区调换
 */
function handleChangeSameArea(data, isRandom = false, { apiResults }) {
  // 提交表单数据
  const formData = {}
  const $ = layui.$
  // 切换 账号密码是否展示

  let tableInstance

  const renderChangeSameArea = () => {
    tableInstance = layui.table.render({
      elem: '#change-same-area-table',
      // height: 'full-100',
      data: data,
      skin: 'line',
      toolbar: false,
      cols: [
        [
          {
            field: 'region_id',
            title: '所属节点',
            templet: function (d) {
              let field = 'region_id'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return layui.util.escape(items.join(','))
            },
          },
          { field: 'ip', title: 'IP' },
          { field: 'port', title: '端口', width: 100 },
          { field: 'account', title: '用户名' },
          { field: 'pass', title: '密码' },
          { field: 'expire_time', title: '到期时间' },
          {
            field: 'status',
            title: '状态',
            templet: function (d) {
              return d.status == 1 ? '已调换' : '未调换'
            },
          },
        ],
      ],
      done: function () {
        // taggleAccount()
      },
    })
  }

  // 渲染 form 元素
  const renderForm = () => {
    // [{name: '原有账号',value: 0,id: 0,pid: 0}]
    const accounts = window.Accounts || []
    // 渲染自定义账号 单选操作
    const fragement = new DocumentFragment()
    $.each(accounts, function (index, item) {
      fragement.append(
        $(
          `<input
              class="layui-radio"
              type="radio"
              name="account_type"
              value="${item.value}"
              title="${item.name}"
              ${index === 0 ? 'checked' : ''}
              lay-filter="account_type"
            />`
        )[0]
      )
    })
    $('#custom-accounts').html(fragement)
    layui.form.on('radio(account_type)', function (data) {
      toggleAccount()
    })
    layui.form.render() // Rebuild.

    // 渲染下拉组件 - 选择端口
    // layui.xmSelect.render({
    //   el: '#custom-port',
    //   name: 'custom-port',
    //   initValue: '',
    //   filterable: false,
    //   direction: 'up',
    //   initValue: [{ id: 1, name: '系统默认', value: '0' }],
    //   data: [{ id: 1, name: '系统默认', value: '0' }],
    //   model: { icon: 'hidden', label: { type: 'text' } },
    //   clickClose: true,
    //   radio: true,
    //   on: function (data) {
    //     console.log(
    //       '%c #custom-port select >>>',
    //       'background: blue; color: #fff',
    //       data
    //     )
    //   },
    // })
  }

  layui.layer.open({
    type: 1,
    title: isRandom ? '随机地区调换' : '同地区调换',
    shade: 0.1,
    maxmin: false,
    area: ['60%','95%',],
    content: $('#change-same-area-wrapper'),
    btnAlign: 'c',
    btn: ['确认调换', '取消'],
    yes: function (index, layero) {
      let formData = layui.form.val('change-same-area-form')

      if (formData.account_type === 1) {
        // 账号密码必填
        const { account, pass } = formData
        if (!account || !pass) {
          layui.popup.warning('自定义账号需要输入账号与密码')
          return
        }
      }

      layer.load()
      // NOTE: 同地区调换
      APILIST.putExchange(
        {
          type: isRandom ? 2 : 1, // 调换类型:1=同地区,2=随机地区,3=自选地区
          line_id: defaultLineId,
          ids: data.map((item) => item.id).join(','),
          data:[],
          // { region_id: 1, number: 1 }[],
          // data: data.map((item) => ({
          //   region_id: item.region_id,
          //   number: 1,
          // })),
          ...formData,
        },
        (res) => {
          layer.closeAll()
          layer.msg(res.msg,{time: 5000})
          window.refreshTable()
        }
      )
    },
    btn2: function (index, layero) {
      layer.close(index)
    },
    success: function () {
      renderChangeSameArea()
      renderForm()
    },
  })
}

// 指定地区调换IP
function handleChangeAreaIP(data) {
  const $ = layui.$
  // 选中数据的 [id,]
  const ids = data.map((item) => item.id)
  const SEL_MAX_COUNT = ids.length
  let CURRENT_AREA_MAX_CHANGE_COUNT = 0 // 当前区域最大调换次数
  let selnodes = null // 选中的数据
  let nodes = null // 当前查询出来的总数据列表

  // 查询节点 `queryParams`
  const searchNodesFormData = {
    line_id: defaultLineId,
    area_id: '',
    game_id: data[0].game_id,
  }

  function fetchLines() {
    APILIST.getLines(
      {
        user_id: data[0].user_id,
        ids,
      },
      (list) => {
        if (list && list.length)
          CURRENT_AREA_MAX_CHANGE_COUNT = list[0].surplus_exchange_number || 0

        // {id, name}[]
        const foragment = new DocumentFragment()
        $.each(list, function (index, item) {
          foragment.appendChild(
            $(
              `<li data-id="${item.line_id}" data-max-number="${
                item.surplus_exchange_number
              }" class="${item.line_id == defaultLineId ? 'layui-this' : ''}">${item.name}</li>`
            )[0]
          )
        })
        $('div[lay-filter="change-same-area-tab"] .layui-tab-title').html(
          foragment
        )

        renderCountOps()
      }
    )
  }

  /**
   * 格式化表单数据
   */
  function formatFormData() {}

  const openWindow = () => {
    layui.layer.open({
      type: 1,
      title: '自选地区调换',
      shade: 0.1,
      maxmin: false,
      area: ['98%', '95%'],
      content: $('#change-same-area-wrapper'),
      btnAlign: 'c',
      btn: ['确认调换', '取消'],
      yes: function (index, layero) {
        if (SEL_MAX_COUNT > CURRENT_AREA_MAX_CHANGE_COUNT)
          return layui.layer.msg('剩余调换次数不足')
        // NOTE: 自选地区调换
        if (!selnodes) return layui.layer.msg('请选择节点')

        let formData = layui.form.val('change-same-area-form')
        if (formData.account_type == 1) {
          // 账号密码必填
          const { account, pass } = formData
          if (!account || !pass)
            return layui.popup.warning('自定义账号需要输入账号与密码')
        }

        const list = Object.entries(selnodes).reduce(
          (accumulator, [region_id, item]) => {
            accumulator.push({
              region_id,
              number: item.number,
            })
            return accumulator
          },
          []
        )

        const list_total = list.reduce(function(sum, item) {
          return sum + item.number;
        }, 0);

        if (list_total < SEL_MAX_COUNT) return layui.layer.msg('选择节点不足')

        layui.layer.load()
        // NOTE: 同地区调换
        APILIST.putExchange(
          {
            ...formatFormData(),
            type: 3, // 调换类型:1=同地区,2=随机地区,3=自选地区
            line_id: defaultLineId,
            // game_id: data[0].game_id,
            ids: data.map((item) => item.id).join(','),
            data: list, // { region_id, number }[]
            line_id_new:searchNodesFormData.line_id,
            ...formData,
          },
          (res) => {
            layer.closeAll()
            window.refreshTable()
            layer.alert(res.msg)
            // TODO
            // setTimeout(() => {
            //   // 弹出确定ip列表
            //   renderSuccessWindowList(res.data)
            // }, 600)
          }
        )
        // --- end ---
      },
      btn2: function (index, layero) {
        $('#change-same-area-wrapper').removeClass('appoint')
        layer.close(index)
      },

      success: function () {
        $('#change-same-area-table').append(
          $('<div class="gameinfo_citys"></div>')
        )
        $('#change-same-area-table').append(
          $('<ul class="nodes-wrapper"></ul>')
        )
        $('input.number-input-value').val(ids.length)
        setTimeout(() => {
          showHideElement()
          renderForm()
          renderAddresList()
          renderNodes()
          fetchLines()
        }, 60)
        // renderChangeSameArea()
        // renderForm()
      },
    })
  }

  // 展示隐藏的自动输入
  function showHideElement() {
    $('div.layui-form-item[type="appoint"]').show()
  }

  // 渲染Radio&select
  // 渲染 form 元素
  const renderForm = () => {
    // [{name: '原有账号',value: 0,id: 0,pid: 0}]
    const accounts = window.Accounts || []
    // 渲染自定义账号 单选操作
    const fragement = new DocumentFragment()
    $.each(accounts, function (index, item) {
      fragement.append(
        $(
          `<input
              class="layui-radio"
              type="radio"
              name="account_type"
              value="${item.value}"
              title="${item.name}"
              ${index === 0 ? 'checked' : ''}
              lay-filter="account_type"
            />`
        )[0]
      )
    })
    $('#custom-accounts').html(fragement)
    layui.form.on('radio(account_type)', function (data) {
      toggleAccount()
    })
    layui.form.render() // Rebuild.
    // 渲染下拉组件 - 选择端口
    // layui.xmSelect.render({
    //   el: '#custom-port',
    //   name: 'custom-port',
    //   filterable: false,
    //   direction: 'up',
    //   initValue: [{ id: 1, name: '系统默认', value: '0' }],
    //   data: [{ id: 1, name: '系统默认', value: '0' }],
    //   model: { icon: 'hidden', label: { type: 'text' } },
    //   clickClose: true,
    //   radio: true,
    //   on: function (data) {
    //     console.log(
    //       '%c #custom-port select >>>',
    //       'background: blue; color: #fff',
    //       data
    //     )
    //   },
    // })
  }

  // #change-same-area-table
  function renderAddresList() {
    // 渲染地址列表
    function getCitys(callback) {
      $.ajax({
        url: '/app/admin/v1-api/getAreaList',
        type: 'GET',
        success: function (res) {
          if (res.code) {
            layui.layer.msg(res.msg)
            return
          }
          const list = res.data || []
          callback && callback(list)
        },
      })
    }

    const renderCitys = (list = []) => {
      const $parent = $('.gameinfo_citys')
      if (!list.length) {
        $parent.html(
          '<i style="color: #999; user-select: none">暂无相关城市</i>'
        )
        return
      }
      const fragement = new DocumentFragment()
      const setButton = (name, id = 'all') =>
        $(
          `<button type="button" plain class="pear-btn pear-btn-xs " data-id="${id}">${name}</button>`
        )[0]
      fragement.appendChild(setButton('全部', 'all'))
      $.each(list, function (index, item) {
        fragement.appendChild(setButton(item.name, item.id))
      })
      // fragement.firstChild.classList.addClass('pear-btn-primary')
      $parent.html(fragement)
      $('.gameinfo_citys button:eq(0)').addClass('pear-btn-primary')
    }
    getCitys(renderCitys)
  }

  function renderNodes() {
    layui.layer.load()
    function getServices(formData, callback) {
      $.ajax({
        url: '/app/admin/v1-api/getRegionList',
        type: 'POST',
        data: {
          ...formData,
        },
        success: function (res) {
          if (res.code) {
            layui.layer.msg(res.msg)
            return
          }
          const list = res.data || []
          nodes = list
          callback && callback(list)
        },
      })
    }

    function renderNode(list = []) {
      const fragement = new DocumentFragment()
      $.each(list, function (index, item) {
        const needDisabled = item.surplus_number <= 0 // 暂无可售出服务IP.
        fragement.append(
          $(`<li
              class="service"
              data-id="${item.id}"
              data-type="${item.type}"
              data-line-id="${item.line_id}"
              data-area-id="${item.area_id}"
              data-type-id="${item.type_id}"
              data-sale="${needDisabled ? 0 : 1}"
            >
              <div class="flex align-center justify-between">
                <span class="nodes-name" title="${item.name}">${item.name}</span>
                <input
                  name="service_${item.area_id}_${item.id}"
                  class="layui-input layui-input-sm"
                  type="number"
                  min="0"
                  value="${item.number || 0}"
                  max="${item.surplus_number}"
                  placeholder="数量"
                  style="max-width: 80px; display: ${
                    needDisabled ? 'none' : 'block'
                  }"
                />
              </div>
              <div class="middleinfos">
                <span>${item.area_name}</span>
                <span>
                  <i class="layui-icon layui-icon-wifi"></i>
                  ISP:
                  <i class="text-color-blue signal-from">${
                    item.operator_name
                  }</i>
                </span>
              </div>
              <div class="flex justify-between btns">
                <!-- 总量&可售 .layui-btn-danger -->
                <button class="pear-btn pear-btn-primary pear-btn-sm pear-btn-${
                  needDisabled ? 'disabled' : ''
                }">
                  总量:${item.ip_number}
                </button>
                <button class="pear-btn pear-btn-primary pear-btn-sm pear-btn-${
                  needDisabled ? 'disabled' : ''
                }" >
                  可售:${item.surplus_number}
                </button>
              </div>
            </li>`)[0]
        )
      })
      if (!list.length) {
        fragement.append(
          $(`<i style="color: #999; user-select: none">暂无可售出服务</i>`)[0]
        )
      }
      $('ul.nodes-wrapper').html(fragement)
      layui.layer.closeAll('loading')
    }

    const getNum = (id) => {
      const temp = selnodes || {} // default object
      if (Object.getOwnPropertyNames(temp).includes(`${id}`)) {
        return temp[id].number
      }
      return 0
    }

    getServices(searchNodesFormData, (list = []) => {
      list = list.map((item) => ({
        ...item,
        number: getNum(item.id),
      }))
      nodes = list
      renderNode(list)
    })
  }

  openWindow()
  $('#change-same-area-wrapper').addClass('appoint')
  renderCountOps()

  // 上传成功之后的 订单数据
  function renderSuccessWindowList(list) {
    const dataStr = list
      .map(
        (item) =>
          `${item.ip}|${item.port}|${item.account}|${item.pass}|${item.expire_time}`
      )
      .join('\n')
    const closedExecute = () => {
      // clean form data.
      selnodes = null
      $('input[name="account"]').val('')
      $('input[name="pass"]').val('')
      // $('input[name="group_name"]').val()
      // $('input[name="remark"]').val()
      $('#autoinput-cancel').click()
      window.refreshTable()
    }

    layer.open({
      type: 1,
      title: '订单数据',
      content: $('.order-confirm-wrapper'),
      btnAlign: 'r',
      btn: ['文本导出', '一键复制', '关闭'],
      area: ['60%', '95%'],
      yes: function (index, layero) {
        // 设置文本导出
        downloadTextAsFile(dataStr, '订单数据.txt')
      },
      btn2: function (index, layero) {
        copyText(dataStr)
      },
      btn3: function (index, layero) {
        closedExecute()
        layer.close(index)
      },
      cancel: function (index) {
        closedExecute()
        layer.close(index)
      },
      success: function () {
        layui.table.render({
          elem: '#confirm-order-table',
          height: 'full',
          data: list,
          skin: 'line',
          toolbar: false,
          cols: [
            [
              { field: 'ip', title: 'IP' },
              { field: 'port', title: '端口', width: 90 },
              { field: 'account', title: '用户名' },
              { field: 'pass', title: '密码' },
              { field: 'expire_time', title: '到期时间' },
            ],
          ],
        })
      },
    })
  }

  // 切换分区
  layui.element.on('tab(change-same-area-tab)', function (data) {
    const targetElement = $(data.elem.context)
    const lineId = targetElement.data('id')
    const maxCount = targetElement.data('max-number')

    if (lineId === searchNodesFormData.line_id) return // 防止多次点击请求
    CURRENT_AREA_MAX_CHANGE_COUNT = maxCount || 0
    if (searchNodesFormData.area_id !== '') {
      cleanCitysStatus(($btns) => {
        $btns.eq(0).addClass('pear-btn-primary')
      })
    }
    $('ul.nodes-wrapper').html('')
    // 根据`line_id`重新查询数据
    searchNodesFormData.line_id = lineId
    renderNodes()
    renderCountOps()
  })

  /**
   * @description 清除城市选中状态
   */
  function cleanCitysStatus(callback) {
    const $btns = $('.gameinfo_citys button')
    $.each($btns, (index, btn) => $(btn).removeClass('pear-btn-primary'))
    callback && callback($btns)
  }

  // 清空选择
  function cleanSelect() {
    const $lis = $('.nodes-wrapper li')
    $.each($lis, function (index, liElement) {
      const sale = $(liElement).attr('data-sale')
      if (sale == 1) {
        $(liElement).find('input[type="number"]').val('')
      }
    })
    selnodes = null
  }

  // 重新渲染节点
  function reRenderServiceFlag(removeClass = false) {
    const $lis = $('.nodes-wrapper li')
    $.each($lis, function (index, liElement) {
      const val = Number($(liElement).find('input[type="number"]').val())
      if (val && !removeClass) {
        $(liElement).addClass('flag')
      } else {
        $(liElement).removeClass('flag')
      }
    })
  }

  /**
   * @description 检查并计算选中的服务数量(地区、IP、金币)
   */
  function renderCountOps(objs = {}) {
    const { area = 0, ip = 0 } = objs
    $('#max-count').text(CURRENT_AREA_MAX_CHANGE_COUNT)
    $('#wait-count').text(ids.length)
    $('#sel-area-count').text(area)
    $('#sel-ip-count').text(ip)
    // $('#sel-score-count').text(parseFloat(score))
  }

  // 获取选中的服务
  function formatCountValidLi(selnodes) {
    if (!selnodes) return { area: 0, ip: 0, num: 0 }

    const list = Object.entries(selnodes)

    const areaN = new Set()
    const ipN = list.length
    let num = 0 // 数量

    for (const [id, item] of list) {
      areaN.add(item.area_id)
      num += item.number || 1
      // ipN.add(id)
    }

    return {
      area: areaN.size,
      ip: ipN,
      num,
    }
  }

  // 更新显示
  function updateShowTips(selnodes) {
    const ds = formatCountValidLi(selnodes)
    layui.layer.msg(`已选 ${ds.area} 个地区, ${ds.num} 个IP`)
    renderCountOps(
      Object.assign(ds, {
        // score: ds.num * score,
        ip: ds.num, // ip总数量、不是ip服务器
      })
    )
  }

  // 筛选城市
  $('.gameinfo_citys').on('click', 'button', function () {
    const $btn = $($(this).context)
    const isSel = $btn.hasClass('pear-btn-primary')
    if (isSel) return // 已经就是选中的不进行选择
    let id = $btn.attr('data-id')
    if (id === 'all') id = ''
    cleanCitysStatus(() => {
      $btn.addClass('pear-btn-primary')
      searchNodesFormData.area_id = id
      renderNodes()
    })
  })

  // 监听服务 input change
  $('.nodes-wrapper').on('change', 'input[type="number"]', function (data) {
    const id = $(this).parents('li.service').attr('data-id')

    console.log(
      '%c select length >>>',
      'background: blue; color: #fff',
      selnodes
    )

    const val = Number($(this).val())

    if (val > SEL_MAX_COUNT)
      return layer.msg('仅可选择' + SEL_MAX_COUNT + '个节点')

    if (isNaN(val) || val <= 0) {
      layer.msg('数据格式错误,请重新输入')
      $(this).val('')
      removeSelNode(id)
      renderCountOps() // clean show tips.
      reRenderServiceFlag(1)
      return
    }

    const item = nodes.find((node) => node.id == id)
    setSelNode({
      ...item,
      number: val,
    })
    updateShowTips(selnodes)
    reRenderServiceFlag()
    // 此处需要加判断不能超过 `SEL_MAX_COUNT` 数量的提示
    if (selnodes) {
      let NNumber = Object.entries(selnodes).reduce(
        (as, [, node]) => (as += Number(node.number)),
        0
      )
      if (NNumber > SEL_MAX_COUNT)
        return layer.msg('仅可选择' + SEL_MAX_COUNT + '个节点')
    }
  })

  // 自动输入的逻辑
  // 自动输入 - 确定
  $('#autoinput-confirm').on('click', function () {
    if (SEL_MAX_COUNT > CURRENT_AREA_MAX_CHANGE_COUNT)
      return layui.layer.msg('剩余调换次数不足')
    const num = $('input.number-input-value').val()
    if (!num) return layui.layer.msg('请输入有效数量')
    autoSelect()
    reRenderServiceFlag()
    updateShowTips(selnodes)
  })

  $('#autoinput-cancel').on('click', function () {
    $('input.number-input-value').val(SEL_MAX_COUNT)
    cleanSelect()
    renderCountOps()
    reRenderServiceFlag(1)
  })

  // 自动选择服务器
  function autoSelect() {
    cleanSelect()

    const autoCount = Number($('input.number-input-value').val() || 0) // 自动选择数量

    if (isNaN(autoCount)) {
      $('input.number-input-value').val('')
      layui.layer.msg('请输入正确的数量')
      return
    }

    const $lis = $('.nodes-wrapper li')
    const nodeLen = nodes.length

    // 可售出总ip数
    let initialVal = 0 // 可被选择的总 ip 数量
    const total = nodes.reduce(
      (pre, cur) => (pre += Number(cur.surplus_number)),
      initialVal
    )

    // 无可售出节点计算
    // 节点中无可售出数量
    const initialNLVal = 0
    const nLifeNodes = nodes.reduce(
      (pre, cur) => (pre += Number(cur.surplus_number <= 0 ? 1 : 0)),
      initialNLVal
    )

    if (autoCount > total) {
      return layui.layer.msg('自动选择数量错误,不可超过总量')
    }

    let lifeNodeCount = nodeLen - nLifeNodes // 剩余有可出售节点

    if (lifeNodeCount < autoCount) {
      /**
       * @deprecated 剩余节点 少于自动选择数量 执行此处
       * while autoCount
       * for 便利顺序判断是否存在可售出 += 1
       *  不存在继续便利 break
       * while again.
       */
      let s = autoCount
      while (s > 0) {
        const l = function (t) {
          if (s <= 0) return 0
          if (
            nodes[t].surplus_number <=
            Number($($lis.get(t)).find('input[type="number"]').val() || 0)
          )
            return 1
          else {
            s -= 1
            let num = Number(
              $($lis.get(t)).find('input[type="number"]').val() || 0
            )

            num += 1

            $($lis.get(t)).find('input[type="number"]').val(num)

            setSelNode({
              ...nodes[t],
              number: num,
            })
          }
        }

        for (var o, r = 0; r < nodeLen; r++) {
          o = l(r)
          if (0 === o) break
        }
      }
    } else {
      /**
       * @deprecated 自动输入少于剩余节点 执行此处
       * 随机 index
       * 判断是否符合、不复合 do-while 去挑选符合 index； (此处增加条件 new-index 不能存在 随机 index 中存在重新筛选)
       * nodes[index] = 1 填充数据
       */

      let c = [],
        d = new Set()

      if (autoCount > 0) {
        while (d.size < autoCount) {
          var p = Math.floor(Math.random() * nodeLen)
          d.add(p)
        }
        c = Array.from(d)
      }

      for (var h = 0; h < c.length; h++) {
        const liEle = $($lis.get(c[h]))[0]
        if (
          nodes[c[h]].surplus_number <=
          ($(liEle).find('input[type="number"]').val() || 0)
        ) {
          let m = 0
          do {
            m = Math.floor(Math.random() * nodeLen)
          } while (
            c.includes(m) ||
            nodes[m].surplus_number <=
              ($($lis.get(m)[0]).find('input[type="number"]').val() || 0)
          )
          c[h] = m
        }

        $($($lis.get(c[h]))[0])
          .find('input[type="number"]')
          .val(1)

        setSelNode({
          ...nodes[c[h]],
          number: 1,
        })
      }
    }
  }

  function setSelNode(item) {
    // additional key number: count
    const temp = selnodes || {} // default object
    const { id } = item

    let num = Number(item.number)
    if (isNaN(num)) num = 1

    if (Object.getOwnPropertyNames(temp).includes(`${id}`)) {
      temp[id].number = num
    } else temp[id] = Object.assign({}, item)

    selnodes = Object.assign({}, temp)
  }

  function removeSelNode(id) {
    const temp = selnodes || {} // default object
    if (Object.getOwnPropertyNames(temp).includes(`${id}`)) {
      delete temp[id]
    }
  }
}

// 渲染时长(html元素)
function renderBNTimes(list) {
  if (!list.length) return
  const $ = layui.$
  const fragement = new DocumentFragment()
  const setButton = (info, className = '') =>
    $(
      `<button type="button" plain class="pear-btn pear-btn-sm ${className}" data-score="${info.score}" data-type="${info.type}">${info.name}</button>`
    )[0]

  $.each(list, function (index, item) {
    if (item.show)
      if (item.type === 'btn')
        fragement.append(
          setButton(
            {
              ...item,
            },
            'pear-btn-disabled'
          )
        )
      else
        fragement.append(
          setButton(
            {
              ...item,
            },
            item.default ? 'pear-btn-primary' : ''
          )
        )
  })

  $('.bn-times').html(fragement)
}

// 获取当前时长的数据
function setIndexInfo(userExtend, lineId) {
  if (!userExtend) return
  const item = userExtend.find((item) => item.line_id == lineId)
  if (item) {
    const list = formatTiemsArrs(item)
    return list
  }
  return []
}

/**
 * 格式化区域服务数据 - 格式化成数组时长信息
 * @param {object} infos 当前区域的详细信息
 * @returns {array}
 */
function formatTiemsArrs(infos) {
  const { zp_show = 0, yp1_show = 0, rp_show = 0 } = infos
  const tipsArs = [
    yp1_show ? `月卡${parseFloat(infos.yp1)}金币` : undefined,
    zp_show ? `周卡${parseFloat(infos.zp)}金币` : undefined,
    rp_show ? `天卡${parseFloat(infos.rp)}金币` : undefined,
  ].filter(key => key)

  return [
    {
      name: '1天',
      score: infos.rp,
      type: 'rp',
      show: infos.rp_show == '1' && infos.rp_switch,
    },
    {
      name: '7天',
      score: infos.zp,
      type: 'zp',
      show: infos.zp_show == '1' && infos.zp_switch,
    },
    {
      name: '1个月',
      score: infos.yp1,
      type: 'yp1',
      show: infos.yp1_show == '1' && infos.yp1_switch,
      default: true,
    },
    {
      name: '3个月',
      score: infos.yp3,
      type: 'yp3',
      show: infos.yp3_show == '1' && infos.yp3_switch,
    },
    {
      name: '6个月',
      score: infos.yp6,
      type: 'yp6',
      show: infos.yp6_show == '1' && infos.yp6_switch,
    },
    {
      name: '1年',
      score: infos.np,
      type: 'np',
      show: infos.np_show == '1' && infos.np_switch,
    },
  ]
    .concat(
      infos.test_switch == '1'
        ? [
            {
              name: '测试卡2小时',
              score: 0,
              type: 'test2h',
              show: infos.test2h_switch == '1',
            },
            {
              name: '测试卡6小时',
              score: 0,
              type: 'test6h',
              show: infos.test6h_switch == '1',
            },
            {
              name: '测试卡12小时',
              score: 0,
              type: 'test12h',
              show: infos.test12h_switch == '1',
            },
          ]
        : []
    )
    .concat([
      {
        type: 'btn',
        name: tipsArs.join('/'),
        show: Boolean(tipsArs.length),
      },
    ])
}
